package com.zds.passwordbox;

import static androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG;
import static androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.zds.passwordbox.common.Constant;

import java.util.concurrent.Executor;

public class LoginActivity extends AppCompatActivity {

    private Executor executor;
    private BiometricPrompt biometricPrompt;
    private BiometricPrompt.PromptInfo promptInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        executor = ContextCompat.getMainExecutor(this);
        // 配置生物识别提示信息
        setupBiometricPrompt();
        // 检查设备是否支持生物识别及相关状态
        checkBiometricSupport();
        //showBiometricPrompt();

        TextView biometricButton = findViewById(R.id.biometric_button);
        biometricButton.setOnClickListener(v -> showBiometricPrompt());
    }

    private void setupBiometricPrompt() {
        // 创建生物识别提示信息
        promptInfo = new BiometricPrompt.PromptInfo.Builder()
                .setTitle("验证指纹或密码")
                .setSubtitle("使用已录入系统的指纹或锁屏密码解锁")
                //.setNegativeButtonText("Cancel")
                .setAllowedAuthenticators(BIOMETRIC_STRONG | DEVICE_CREDENTIAL)
                .build();

        // 创建BiometricPrompt实例，并设置认证回调
        biometricPrompt = new BiometricPrompt(this, executor,
                new BiometricPrompt.AuthenticationCallback() {
                    @Override
                    public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) {
                        super.onAuthenticationError(errorCode, errString);
                        if (errorCode == BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL) {
                            Toast.makeText(getApplicationContext(),
                                    "Authentication error: 请确定设备至少开启了锁屏密码",
                                    Toast.LENGTH_SHORT).show();
                        }
                        if (errorCode == BiometricPrompt.ERROR_USER_CANCELED) {
                            SharedPreferences.Editor edit = getSharedPreferences(Constant.IS_VERIFIED,
                                    Context.MODE_PRIVATE).edit();
                            edit.putBoolean(Constant.IS_VERIFIED, false);
                            edit.apply();
                        }
                    }

                    @Override
                    public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) {
                        super.onAuthenticationSucceeded(result);
                        SharedPreferences.Editor edit = getSharedPreferences(Constant.IS_VERIFIED,
                                Context.MODE_PRIVATE).edit();
                        edit.putBoolean(Constant.IS_VERIFIED, true);
                        edit.apply();
                        finish();
                    }

                    @Override
                    public void onAuthenticationFailed() {
                        super.onAuthenticationFailed();
                    }
                });
    }

    private void checkBiometricSupport() {
        BiometricManager biometricManager = BiometricManager.from(this);
        switch (biometricManager.canAuthenticate(BIOMETRIC_STRONG | DEVICE_CREDENTIAL)) {
            case BiometricManager.BIOMETRIC_SUCCESS:
                // 应用可以进行生物识别技术进行身份验证，可显示相关提示等（这里暂未额外处理）
                break;
            case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
                Toast.makeText(this, "该设备上没有搭载可用的生物特征功能", Toast.LENGTH_SHORT).show();
                break;
            case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
                Toast.makeText(this, "生物识别功能当前不可用", Toast.LENGTH_SHORT).show();
                break;
            case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
                Toast.makeText(this, "没有录入生物识别数据", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //Intent intent = getIntent();
        //if (intent!= null && (Objects.equals(intent.getAction(), Intent.ACTION_OPEN_DOCUMENT) ||
        //        Objects.equals(intent.getAction(), Intent.ACTION_CREATE_DOCUMENT))) {
        //    // 这是从文件选择器返回，不进行指纹验证
        //    return;
        //}
        showBiometricPrompt();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private void showBiometricPrompt() {
        biometricPrompt.authenticate(promptInfo);
    }
}